package bar.dark.lee.insert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.macro.MacroData;
import bar.dark.lee.macro.MacroListActivity;
import bar.dark.lee.setting.auto.AutoActivity;
import bar.dark.lee.setting.auto.AutoInsertActivity;
import bar.dark.lee.setting.sms.InputData;
import bar.dark.lee.setting.sms.Parser;
import bar.dark.lee.setting.sms.SMSData;
import bar.dark.lee.setting.sms.SMSSettingActivity;
import bar.dark.lee.setting.sms.SmsLoadInbox;

public class InsertOutActivity extends SuperActivity
{
	public static final int REQUEST_CATEGORY = 0;
	public static final int REQUEST_CHECK = 1;
	public static final int REQUEST_CREDIT = 2;
	public static final int REQUEST_BANK = 3;
	public static final int REQUEST_SMS = 4;
	public static final int REQUEST_HALBU = 5;
	
	public static final String HALBU_CARD_NAME = "halbu_card_name";
	public static final String HALBU_DATE = "halbu_date";
	public static final String HALBU_MONEY = "halbu_money";
	public static final String HALBU_MEMO = "memo";
	public static final String HALBU_MONTH = "halbu_month";
	
	private AlertDialog dialog;
	private View dialogView;
	private DBSQLite sql;
	
	private RadioButton realRadioButton;
	private RadioButton bankRadioButton;
	private RadioButton checkRadioButton;
	private RadioButton creditRadioButton;
	
	private View smsView;
	private Button insertSmsButton;
	private Button insertHalBuButton;
	
	private TextView balanceText;
	private TextView balanceMoney;
	private View bankView;
	private View checkView;
	private View creditView;
	private TextView bankTextView;
	private TextView checkTextView;
	private TextView creditTextView;
	
	private View dateButton;
	private TextView dateTextView;
	private View categoryView;
	private TextView categoryTextView;
	private EditText money;
	private View memoView;
	private EditText memo;
	private Button insertButton;
	
	private Button minusButton;
	
	private Button macroDeleteButton;
	
	private ArrayList<String> categoryList;
	private ArrayList<String> bankList;
	private ArrayList<String> checkList;
	private ArrayList<String> creditList;
	
	// 날짜
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private int linkId = -1;
	
//	private int firstBankRadio = 0;
	
	public static boolean btnEnable = true;
	public static int asyncFlag = 0;
	
	private boolean fromMacro;
	
	private String from;
	
	private MacroData macroData;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.insert_outmoney);
		
		Intent intent = getIntent();
		from = intent.getStringExtra(MacroListActivity.FROM);
		
		if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_STRING))
		{
			fromMacro = true;
			setTitle("빠른입력 추가");
			((TextView)findViewById(R.id.insertOutHelp)).setText("빠른입력 내용을 추가합니다.");
			setGoneTipButton();
		}
		else if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_UPDATE))
		{
			fromMacro = true;
			setTitle("빠른입력 수정");
			((TextView)findViewById(R.id.insertOutHelp)).setText("빠른입력 내용을 수정합니다.");
			setGoneTipButton();
		}
		else
		{
			fromMacro = false;
			setGoneTitle();
		}
		
		initFindView();
		initClickListener();
		initDataSetting();
		
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	int flag = pref.getInt(BDConstents.OUT_MANAGER_SELECT_FLAG, 0);
    	
    	if (flag == 1)
		{
			setCheckRadioClick();
		}
    	else if (flag == 2)
    	{
    		setBankRadioClick();
    	}
    	else if (flag == 3)
    	{
    		setCreditRadioClick();
    	}
    	else
    	{
    		setRealRadioClick();
    	}
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		
		int flag = 0;
		
		if (checkRadioButton.isChecked())
		{
			flag = 1;
		}
		else if (bankRadioButton.isChecked())
		{
			flag = 2;
		}
		else if (creditRadioButton.isChecked())
		{
			flag = 3;
		}
		else
		{
			flag = 0;
		}
		
		editor.putInt(BDConstents.OUT_MANAGER_SELECT_FLAG, flag);
		
		editor.commit();
	}
	
	private void initFindView()
	{
		realRadioButton = (RadioButton) findViewById(R.id.insertOutRealRadio);
		bankRadioButton = (RadioButton) findViewById(R.id.insertOutBankRadio);
		checkRadioButton = (RadioButton) findViewById(R.id.insertOutCheckRadio);
		creditRadioButton = (RadioButton) findViewById(R.id.insertOutCreditRadio);
		
		smsView = findViewById(R.id.insertOutSMSView);
		insertSmsButton = (Button) findViewById(R.id.insertOutSMSButton);
		insertHalBuButton = (Button) findViewById(R.id.insertOutHalBuButton);
		
		balanceText = (TextView) findViewById(R.id.insertOutBalanceText);
		balanceMoney = (TextView) findViewById(R.id.insertOutBalance);
		bankView = findViewById(R.id.insertOutBankView);
		checkView = findViewById(R.id.insertOutCheckView);
		creditView = findViewById(R.id.insertOutCreditView);
		bankTextView = (TextView) findViewById(R.id.insertOutBankKind);
		checkTextView = (TextView) findViewById(R.id.insertOutCheckKind);
		creditTextView = (TextView) findViewById(R.id.insertOutCreditKind);
		
		dateButton = findViewById(R.id.insertOutDate);
		dateTextView = (TextView) findViewById(R.id.insertOutDateTextView);
		categoryView = findViewById(R.id.insertOutCategory);
		categoryTextView = (TextView) findViewById(R.id.insertOutCategoryTextView);
		
		money = (EditText) findViewById(R.id.insertOutMoney);
		EditTextInputFilter.filteringMoneyEditText(money);
		
		memoView = findViewById(R.id.insertOutMemoView);
		memo = (EditText) findViewById(R.id.insertOutMemo);
		insertButton = (Button) findViewById(R.id.insertOutInsertButton);
		
		minusButton = (Button) findViewById(R.id.insertOutMinusButton);
		minusButton.setVisibility(View.GONE);
		
		macroDeleteButton = (Button) findViewById(R.id.insertMacroDeleteButton);
	}
	
	private void initDataSetting()
	{
		if (fromMacro)
		{
			dateButton.setVisibility(View.GONE);
			((View)findViewById(R.id.insertOutDateLine)).setVisibility(View.GONE);
			insertHalBuButton.setVisibility(View.GONE);
			
			if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_STRING))
			{
				insertButton.setText("빠른 입력 추가");
				macroDeleteButton.setVisibility(View.GONE);
			}
			else if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_UPDATE))
			{
				insertButton.setText("빠른 입력 수정");
				macroDeleteButton.setVisibility(View.VISIBLE);
			}
		}
		else
		{
			macroDeleteButton.setVisibility(View.GONE);
		}
		
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
		toMonth = cal.get(Calendar.MONTH);
		toDay = cal.get(Calendar.DAY_OF_MONTH);
		
		dateTextView.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
		
		sql.selectMapTile(this, "SELECT kind FROM category_out_list ORDER BY count DESC", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				categoryList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("kind");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					categoryList.add(kind);
					c.moveToNext();
				}
				
				if (categoryList.size() < 1)
				{
					String memo = "없음";
					categoryList.add(memo);
					categoryView.setClickable(false);
				}
				
				categoryTextView.setText(categoryList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				bankList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					bankList.add(kind);
					c.moveToNext();
				}
				
				if (bankList.size() < 1)
				{
					String memo = "없음";
					bankList.add(memo);
					bankView.setClickable(false);
					bankView.setTag(false);
				}
				else
				{
					bankView.setClickable(true);
					bankView.setTag(true);
				}
				
				bankTextView.setText(bankList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM check_card b, checkcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM check_card b, checkcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				checkList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					checkList.add(kind);
					c.moveToNext();
				}
				
				if (checkList.size() < 1)
				{
					String memo = "없음";
					checkList.add(memo);
					checkView.setClickable(false);
					checkView.setTag(false);
				}
				else
				{
					checkView.setClickable(true);
					checkView.setTag(true);
				}
				
				checkTextView.setText(checkList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				creditList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					creditList.add(kind);
					c.moveToNext();
				}
				
				if (creditList.size() < 1)
				{
					String memo = "없음";
					creditList.add(memo);
					creditView.setClickable(false);
					creditView.setTag(false);
				}
				else
				{
					creditView.setClickable(true);
					creditView.setTag(true);
				}
				
				creditTextView.setText(creditList.get(0).toString());
			}
		});
		
		setBalanceRealMoney();
		
		if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_UPDATE))
		{
			MacroData data = getIntent().getParcelableExtra(MacroListActivity.MACRO_DATA);
			
			String query = "SELECT * FROM macro_list " +
					"WHERE id = " + data.getId() + ";";
			
			macroData = null;
			
			sql.selectMapTile(superContext, query, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int count = c.getCount();
					
					c.moveToFirst();
					
					if (count != 0)
					{
						int idIndex = c.getColumnIndex("id");
						int typeIndex = c.getColumnIndex("type");
						int titleIndex = c.getColumnIndex("title");
						int inMoneyIndex = c.getColumnIndex("inmoney");
						int outMoneyIndex = c.getColumnIndex("outmoney");
						int postMoneyIndex = c.getColumnIndex("postmoney");
						int categoryIndex = c.getColumnIndex("category");
						int moneykindIndex = c.getColumnIndex("moneykind");
						int checkIndex = c.getColumnIndex("checkbox");
						int memoIndex = c.getColumnIndex("memo");
						
						for (int i = 0; i < count; i++)
						{
							macroData = new MacroData();
							macroData.setId(c.getInt(idIndex) + "");
							macroData.setType(c.getString(typeIndex));
							macroData.setTitle(c.getString(titleIndex));
							macroData.setInmoney(c.getString(inMoneyIndex));
							macroData.setOutmoney(c.getString(outMoneyIndex));
							macroData.setPostmoney(c.getString(postMoneyIndex));
							macroData.setMoneykind(c.getString(moneykindIndex));
							macroData.setCategory(c.getString(categoryIndex));
							macroData.setCheck(c.getString(checkIndex));
							macroData.setMemo(c.getString(memoIndex));
							
							c.moveToNext();
						}
					}
				}
			});
			
			if (macroData == null)
			{
				BDUtil.showDialogFinish(superContext, "경고", "데이터를 가져오는데 실패 했습니다.");
			}
			else
			{
				if (macroData.getType().equals(BDConstents.REAL_TYPE))
				{
					categoryTextView.setText(macroData.getCategory());
					memo.setText(macroData.getMemo());
					money.setText(macroData.getOutmoney());
					setRealRadioClick();
				}
				else if (macroData.getType().equals(BDConstents.BANK_TYPE))
				{
					categoryTextView.setText(macroData.getCategory());
					memo.setText(macroData.getMemo());
					money.setText(macroData.getOutmoney());
					bankTextView.setText(macroData.getMoneykind());
					setBankRadioClick();
				}
				else if (macroData.getType().equals(BDConstents.CHECK_TYPE))
				{
					categoryTextView.setText(macroData.getCategory());
					memo.setText(macroData.getMemo());
					money.setText(macroData.getOutmoney());
					checkTextView.setText(macroData.getMoneykind());
					setCheckRadioClick();
				}
				else if (macroData.getType().equals(BDConstents.CREDIT_TYPE))
				{
					categoryTextView.setText(macroData.getCategory());
					memo.setText(macroData.getMemo());
					money.setText(macroData.getPostmoney());
					creditTextView.setText(macroData.getMoneykind());
					setCreditRadioClick();
				}
			}
		}
	}
	
	private void setRealRadioClick()
	{
		if (checkRadioButton.isChecked())
		{
			checkRadioButton.setChecked(false);
		}
		else if (creditRadioButton.isChecked())
		{
			creditRadioButton.setChecked(false);
		}
		else if (bankRadioButton.isChecked())
		{
			bankRadioButton.setChecked(false);
		}
		
//		firstBankRadio = 0;
		smsView.setVisibility(View.GONE);
		realRadioButton.setChecked(true);
		bankView.setVisibility(View.GONE);
		checkView.setVisibility(View.GONE);
		creditView.setVisibility(View.GONE);
		minusButton.setVisibility(View.GONE);
		
		setBalanceRealMoney();
	}
	
	private void setCheckRadioClick()
	{
		if (creditView.getVisibility() == View.VISIBLE)
		{
			creditView.setVisibility(View.GONE);
			
		}
		else if (bankView.getVisibility() == View.VISIBLE)
		{
			bankView.setVisibility(View.GONE);
		}
		
//		firstBankRadio = 1;
		smsView.setVisibility(View.VISIBLE);
		insertHalBuButton.setVisibility(View.GONE);
		checkView.setVisibility(View.VISIBLE);
		minusButton.setVisibility(View.GONE);
		
		checkRadioButton.setChecked(true);
		realRadioButton.setChecked(false);
		bankRadioButton.setChecked(false);
		creditRadioButton.setChecked(false);
		
		setBalanceCheckMoney();
	}
	
	private void setCreditRadioClick()
	{
		if (checkView.getVisibility() == View.VISIBLE)
		{
			checkView.setVisibility(View.GONE);
		}
		else if (bankView.getVisibility() == View.VISIBLE)
		{
			bankView.setVisibility(View.GONE);
		}
		
//		firstBankRadio = 2;
		
		minusButton.setVisibility(View.VISIBLE);
		smsView.setVisibility(View.VISIBLE);
		
		if (!fromMacro)
		{
			insertHalBuButton.setVisibility(View.VISIBLE);
		}
		
		creditView.setVisibility(View.VISIBLE);
		
		creditRadioButton.setChecked(true);
		realRadioButton.setChecked(false);
		bankRadioButton.setChecked(false);
		checkRadioButton.setChecked(false);
		
		setBalanceCreditMoney();
	}
	
	private void setBankRadioClick()
	{
		if (creditView.getVisibility() == View.VISIBLE)
		{
			creditView.setVisibility(View.GONE);
		}
		else if (checkView.getVisibility() == View.VISIBLE)
		{
			checkView.setVisibility(View.GONE);
		}
		
//		firstBankRadio = 3;
		smsView.setVisibility(View.VISIBLE);
		insertHalBuButton.setVisibility(View.GONE);
		bankView.setVisibility(View.VISIBLE);
		minusButton.setVisibility(View.GONE);
		
		bankRadioButton.setChecked(true);
		realRadioButton.setChecked(false);
		checkRadioButton.setChecked(false);
		creditRadioButton.setChecked(false);
		
		setBalanceBankMoney();
	}
	
	private void initClickListener()
	{
		realRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setRealRadioClick();
			}
		});
		
		checkRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCheckRadioClick();
			}
		});
		
		creditRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCreditRadioClick();
			}
		});
		
		bankRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setBankRadioClick();
			}
		});
		
		insertSmsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new ShowDialog().execute(BDUtil.asyncFlag, 3);
			}
		});
		
		insertHalBuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertOutActivity.this, AutoInsertActivity.class);
				intent.putExtra(AutoInsertActivity.REQUEST_KEY, AutoInsertActivity.INSERT_HALBU);
				intent.putExtra(AutoActivity.AUTO_UPDATE_DELECT_FLAG, AutoActivity.AUTO_INSERT);
				startActivityForResult(intent, REQUEST_HALBU);
			}
		});
		
		categoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertOutActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, categoryList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryTextView.getText().toString());
				intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_OUT_TYPE);
				intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_OUT_TYPE_STRING);
				startActivityForResult(intent, REQUEST_CATEGORY);
			}
		});
		
		checkView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertOutActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, checkList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, checkTextView.getText().toString());
				startActivityForResult(intent, REQUEST_CHECK);
			}
		});
		
		creditView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertOutActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, creditList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, creditTextView.getText().toString());
				startActivityForResult(intent, REQUEST_CREDIT);
			}
		});
		
		bankView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertOutActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, bankList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, bankTextView.getText().toString());
				startActivityForResult(intent, REQUEST_BANK);
			}
		});
		
		dateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
						
						toYear = year;
						toMonth = monthOfYear;
						toDay = dayOfMonth;
						
					}
				}, toYear, toMonth, toDay);
				
				cpd.show();
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (money.length() < 1)
				{
					BDUtil.showDialog(InsertOutActivity.this, "금액오류", "금액을 정확히 입력해주세요.");
					return;
				}
				
				if (checkRadioButton.isChecked())
				{
					boolean flag = (Boolean) checkView.getTag();
					
					if (flag == false)
					{
						BDUtil.showDialogManager(superContext, "체크카드가 하나도 없습니다.");
						return;
					}
				}
				else if (creditRadioButton.isChecked())
				{
					boolean flag = (Boolean) creditView.getTag();
					
					if (flag == false)
					{
						BDUtil.showDialogManager(superContext, "신용카드가 하나도 없습니다.");
						return;
					}
				}
				else if (bankRadioButton.isChecked())
				{
					boolean flag = (Boolean) bankView.getTag();
					
					if (flag == false)
					{
						BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
						return;
					}
				}
				
				if (fromMacro)
				{
					if (memo.getText().toString().trim().length() < 1)
					{
						BDUtil.showDialog(InsertOutActivity.this, "메모오류", "메모를 입력해주세요. 해당 빠른입력의 이름으로 적용됩니다.");
						return;
					}
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		});
		
		minusButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				money.setText("-");
				money.setSelection(money.getText().toString().length());
			}
		});
		
		macroDeleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				BDUtil.showSelectDialog(superContext, "경고", "정말로 삭제하시겠습니까?", 
						new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						new ShowDialog().execute(BDUtil.asyncFlag, 5);
					}
				}, new DialogInterface.OnClickListener()
				{
					
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
					}
				});
			}
		});
	}
	
	private void insertOutData() throws Exception
	{
		if (fromMacro)
		{
			String type = "";
			String moneyKind = "";
			
			if (realRadioButton.isChecked())
			{
				type = "0";
				moneyKind = "현금";
			}
			else if (checkRadioButton.isChecked())
			{
				type = "2";
				moneyKind = checkTextView.getText().toString();
			}
			else if (bankRadioButton.isChecked())
			{
				type = "1";
				moneyKind = bankTextView.getText().toString();
			}
			else if (creditRadioButton.isChecked())
			{
				type = "3";
				moneyKind = creditTextView.getText().toString();
			}
			
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("category", categoryTextView.getText().toString());
			
			if (type.equals("3"))
			{
				map.put("postmoney", BDUtil.getCommaDel(money.getText().toString()));
			}
			else
			{
				map.put("outmoney", BDUtil.getCommaDel(money.getText().toString()));
			}
			//String date = dateTextView.getText().toString();
			//date = date.replace(" ", "");
			//date = date.replace("-", "");
			//map.put("date", date);
			map.put("moneykind", moneyKind);
			map.put("type", type);
			map.put("memo", memo.getText().toString());
			map.put("title", memo.getText().toString());
			
			if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_STRING))
			{
				map.put("checkbox", "0");
				sql.insert(superContext, map, "macro_list");
			}
			else if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_UPDATE))
			{
				String [] whereArgs = new String[]{macroData.getId()};
				sql.update(superContext, "macro_list", map, "id = ?", whereArgs);
			}
			
			//sql.insert(superContext, map, "in_out");
		}
		else
		{
			String type = "";
			String moneyKind = "";
			
			if (realRadioButton.isChecked())
			{
				realOutInsert();
				
				type = BDConstents.REAL_TYPE;
				moneyKind = "현금";
			}
			else if (checkRadioButton.isChecked())
			{
				if (!checkOutInsert())
				{
					throw new Exception();
				}
				
				type = BDConstents.CHECK_TYPE;
				moneyKind = checkTextView.getText().toString();
			}
			else if (creditRadioButton.isChecked())
			{
				if (!creditOutInsert())
				{
					throw new Exception();
				}
				
				type = BDConstents.CREDIT_TYPE;
				moneyKind = creditTextView.getText().toString();
			}
			else if (bankRadioButton.isChecked())
			{
				if (!bankOutInsert())
				{
					throw new Exception();
				}
				
				type = BDConstents.BANK_TYPE;
				moneyKind = bankTextView.getText().toString();
			}
			
			// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
			if (type.equals("") || moneyKind.equals(""))
			{
				throw new Exception();
			}
			
			String date = dateTextView.getText().toString();
			date = date.replace(" ", "");
			date = date.replace("-", "");
			
			// 잔액을 입력한다.
			BalanceQuery balace = new BalanceQuery(superContext);
			balace.setBalance(type, moneyKind);
			
			// 카테고리 카운트 하나 증가
			sql.selectMapTile(this, "SELECT count FROM category_out_list WHERE kind = '" +
					BDUtil.getApostrophe(categoryTextView.getText().toString()) + "';", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int countIndex = c.getColumnIndex("count");
					int count = 0;
					
					c.moveToFirst();
					for (int i = 0; i < c.getCount(); i++)
					{
						count = c.getInt(countIndex);
						c.moveToNext();
					}
					
					count++;
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("count", "" + count);
					String [] whereArgs = new String[]{categoryTextView.getText().toString()};
					sql.update(InsertOutActivity.this, "category_out_list", map, "kind = ?", whereArgs);
				}
			});
		}
	}

	private void realOutInsert()
	{
		setInOutTable("현금", "0");
		
		sql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
				}
				
				money = money.subtract(tempMoney);
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(InsertOutActivity.this, "real_money", map, null, null);
			}
		});
	}

	private int bankId = -1;
	private boolean checkOutInsert()
	{
		linkId = -1;
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '" 
				+ BDUtil.getApostrophe(checkTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int banklinkIndex = c.getColumnIndex("banklink");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					linkId = c.getInt(banklinkIndex);
					c.moveToNext();
				}
			}
		});
		
		if (linkId > -1)
		{
			sql.selectMapTile(InsertOutActivity.this, "SELECT id, money FROM bankbook WHERE id = " + linkId + ";", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
//					int tempMoney = Integer.parseInt(money.getText().toString());
					
					bankId = -1;
					
					int idIndex = c.getColumnIndex("id");
					int moneyIndex = c.getColumnIndex("money");
					
					c.moveToFirst();
					BigDecimal money = BigDecimal.ZERO;
					for (int i = 0; i < c.getCount(); i++)
					{
//						tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
						bankId = c.getInt(idIndex);
						money = money.add(new BigDecimal(c.getString(moneyIndex)));
						c.moveToNext();
					}
					
					money = money.subtract(tempMoney);
					
					if (bankId != -1)
					{
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("money", money.toString());
						String [] whereArgs = new String[]{bankId + ""};
						sql.update(InsertOutActivity.this, "bankbook", map, "id = ?", whereArgs);
					}
					
				}
			});
		}
		else
		{
			return false;
		}
		
		if (bankId == -1)
		{
			return false;
		}
		
		try
		{
			setInOutTable(checkTextView.getText().toString(), "2");
		} catch (Exception e)
		{
			return false;
		}
		
		return true;
	}
	
	private int creditId = -1;
	private boolean creditOutInsert()
	{
		sql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '" 
				+ BDUtil.getApostrophe(creditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				creditId = -1;
				int idIndex = c.getColumnIndex("id");
				int moneyIndex = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
					creditId = c.getInt(idIndex);
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) + tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.add(tempMoney);
				
				if (creditId != -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("outmoney", money.toString());
					String [] whereArgs = new String[]{creditId + ""};
					sql.update(InsertOutActivity.this, "credit_card", map, "id = ?", whereArgs);
				}
			}
		});
		
		if (creditId == -1)
		{
			return false;
		}
		
		try
		{
			setInOutTable(creditTextView.getText().toString(), "3");
		} catch (Exception e)
		{
			return false;
		}
		
		return true;
	}
	
	private boolean bankOutInsert()
	{
		sql.selectMapTile(InsertOutActivity.this, "SELECT id, money FROM bankbook WHERE name = '" 
					+ BDUtil.getApostrophe(bankTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
//				int tempMoney = Integer.parseInt(money.getText().toString());
				
				int idIndex = c.getColumnIndex("id");
				int moneyIndex = c.getColumnIndex("money");
				
				bankId = -1;
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
					bankId = c.getInt(idIndex);
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.subtract(tempMoney);
				
				if (bankId != -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("money", money.toString());
					String [] whereArgs = new String[]{bankTextView.getText().toString()};
					sql.update(InsertOutActivity.this, "bankbook", map, "name = ?", whereArgs);
				}
			}
		});
		
		if (bankId == -1)
		{
			return false;
		}
		
		try
		{
			setInOutTable(bankTextView.getText().toString(), "1");
		} catch (Exception e)
		{
			return false;
		}
		
		return true;
	}
	
	private void setInOutTable(String moneyKind, String type)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("category", categoryTextView.getText().toString());
		
		if (type.equals("3"))
		{
			map.put("postmoney", BDUtil.getCommaDel(money.getText().toString()));
		}
		else
		{
			map.put("outmoney", BDUtil.getCommaDel(money.getText().toString()));
		}
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		map.put("date", date);
		map.put("moneykind", moneyKind);
		map.put("type", type);
		
		map.put("memo", memo.getText().toString());
		
		sql.insert(this, map, "in_out");
	}
	
	private void setBalanceRealMoney()
	{
		sql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("money");
				c.moveToFirst();
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
//					money = money + Integer.parseInt(c.getString(columIndex));
					money = money.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				balanceText.setText("잔액");
				balanceMoney.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	private void setBalanceCheckMoney()
	{
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(checkTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("banklink");
				c.moveToFirst();
				int banklink = 0;
				for (int i = 0; i < count; i++)
				{
					banklink = c.getInt(columIndex);
					c.moveToNext();
				}
				
				sql.selectMapTile(InsertOutActivity.this, "SELECT money FROM bankbook WHERE id = " + banklink, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int count = c.getCount();
						
						int columIndex = c.getColumnIndex("money");
						c.moveToFirst();
//						int money = 0;
						BigDecimal money = BigDecimal.ZERO;
						for (int i = 0; i < count; i++)
						{
//							money = money + Integer.parseInt(c.getString(columIndex));
							money = money.add(new BigDecimal(c.getString(columIndex)));
							c.moveToNext();
						}
						
						balanceText.setText("잔액");
						balanceMoney.setText(BDUtil.getWon(money.toString()) + shape);
					}
				});
			}
		});
	}
	
	private void setBalanceCreditMoney()
	{
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(creditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("outmoney");
				c.moveToFirst();
//				int outmoney = 0;
				BigDecimal outmoney = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
//					outmoney = outmoney + Integer.parseInt(c.getString(columIndex));
					outmoney = outmoney.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				balanceText.setText("카드대금");
				balanceMoney.setText(BDUtil.getWon(outmoney.toString()) + shape);
			}
		});
	}
	
	private void setBalanceBankMoney()
	{
		sql.selectMapTile(InsertOutActivity.this, "SELECT money FROM bankbook WHERE name = '" 
					+ BDUtil.getApostrophe(bankTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("money");
				c.moveToFirst();
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
//					money = money + Integer.parseInt(c.getString(columIndex));
					money = money.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				balanceText.setText("잔액");
				balanceMoney.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CATEGORY)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				categoryTextView.setText(selectData);
			}
			else if (resultCode == RadioDialogActivity.REFRESH_CATEGORY)
			{
				final String beforeCategory = categoryTextView.getText().toString();
				
				sql.selectMapTile(this, "SELECT kind FROM category_out_list ORDER BY count DESC", new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						categoryList = new ArrayList<String>();
						
						int nameIndex = c.getColumnIndex("kind");
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							String kind = c.getString(nameIndex);
							categoryList.add(kind);
							c.moveToNext();
						}
						
						if (categoryList.size() < 1)
						{
							String memo = "없음";
							categoryList.add(memo);
							categoryView.setClickable(false);
						}
						
						categoryTextView.setText(beforeCategory);
					}
				});
			}
		}
		else if (requestCode == REQUEST_CHECK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				checkTextView.setText(selectData);
				
//				if (firstBankRadio == 1)
//				{
//				}
				setBalanceCheckMoney();
			}
		}
		else if (requestCode == REQUEST_CREDIT)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				creditTextView.setText(selectData);
				
//				if (firstBankRadio == 2)
//				{
//				}
				setBalanceCreditMoney();
			}
		}
		else if (requestCode == REQUEST_BANK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				bankTextView.setText(selectData);
				
//				if (firstBankRadio == 3)
//				{
//				}
				setBalanceBankMoney();
			}
		}
		else if (requestCode == REQUEST_HALBU)
		{
			if (resultCode == Activity.RESULT_OK)
			{
//				boolean flag = data.getBooleanExtra(AutoInsertActivity.TODAY_INTRO, false);
//				
//				if (flag)
//				{
//					BDUtil.showDialogOK(this, "알림", 
//							"할부 내역 입력을 위해 초기 화면으로 이동합니다.", 
//							new DialogInterface.OnClickListener()
//					{
//						@Override
//						public void onClick(DialogInterface dialog, int which)
//						{
//							BDUtil.btnEnable = true;
//							BDUtil.asyncFlag = 0;
//							
//							Intent intent = new Intent(superContext, IntroActivitiy.class);
//							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//							startActivity(intent);
//						}
//					});
//				}
//				else
//				{
//				}
				
				finish();
			}
		}
		else if (requestCode == REQUEST_SMS)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				if (dialog != null) {
					dialog.dismiss();
					dialog = null;
				}
				
				String cardName = data.getStringExtra(SMSSettingActivity.CARD_NAME);
				String date = data.getStringExtra(SMSSettingActivity.DATE);
				String money = data.getStringExtra(SMSSettingActivity.MONEY);
				String memo = data.getStringExtra(SMSSettingActivity.MEMO);

				try {
					dateTextView.setText(BDUtil.getDate(
							Integer.parseInt(date.substring(0, 4)), 
							Integer.parseInt(date.substring(4, 6)), 
							Integer.parseInt(date.substring(6, 8))));
					
					if (checkRadioButton.isChecked()) {
						checkTextView.setText(cardName);
						setBalanceCheckMoney();
					} else if (creditRadioButton.isChecked()) {
						creditTextView.setText(cardName);
						setBalanceCreditMoney();
					} else if (bankRadioButton.isChecked()) {
						bankTextView.setText(cardName);
						setBalanceBankMoney();
					} 
					
					this.money.setText(money);
					
					this.memo.setText(memo);
					
				} catch (Exception e) {
					BDUtil.showDialogFinish(InsertOutActivity.this, "알림", "데이터 로딩에 실패했습니다.");
				}
			} 
		}
		else if (requestCode == BDConstents.REQUEST_CALENDAR_PICKER)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String result = data.getStringExtra(BDConstents.REQUEST_CALENDAR_PICKER_STRING);
				dateTextView.setText(BDUtil.getDate(Integer.parseInt(result.substring(0, 4)), 
						Integer.parseInt(result.substring(4, 6)), Integer.parseInt(result.substring(6, 8))));
			}
		}
	}
	
	private void setAddListView(final ArrayList<SMSData> list) 
	{
		if (dialog != null) 
		{
			dialog.dismiss();
			dialog = null;
		}
		
		View view = LayoutInflater.from(this).inflate(R.layout.sms_dialog, null);
		Button button = (Button) view.findViewById(R.id.smsDialog_direct);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				noSMS();
			}
		});
		ListView listView = (ListView) view.findViewById(R.id.smsDialog_listView);
		SMSAdapter adapter = new SMSAdapter(this, R.layout.list_item_sms2, list); 
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(adapter);
		adapter.setNotifyOnChange(true);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(view);
		
		dialog = builder.create();
		dialog.show();
	}
	
	private void noSMS() {
		// 다 실패하면 그냥 직접입력해한다
		if (dialog != null) {
			dialog.dismiss();
			dialog = null;
		}
		
		dialogView = LayoutInflater.from(this).inflate(R.layout.sms_dialog3, null);
		dialogView.findViewById(R.id.smsDialog3_viewNumber).setVisibility(View.GONE);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(dialogView);
		dialogView.findViewById(R.id.smsDialog3_btnConfirm).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String inputNumber = ((EditText)dialogView.findViewById(R.id.smsDialog3_editNumber)).getText().toString().trim();
				String inputMessage = ((EditText)dialogView.findViewById(R.id.smsDialog3_editMessage)).getText().toString().trim();
				
				if (inputMessage.length()==0) {
//					BDUtil.showDialog(SMSActivity.this, "내용누락", "문자 내용을 입력해주세요.");
					BDUtil.showToast(InsertOutActivity.this, "문자 내용을 입력해주세요.");
					return;
				}
				
				int smsType = BDConstents.OUT_SMS;
				boolean flagATM = false;
				//SMSParser2 parser2 = new SMSParser2(inputMessage);
				Parser parser2 = null;
				try {
					parser2 = new Parser(inputMessage);
				} catch (Exception e)
				{
					Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
					return;
				} finally
				{
					if (parser2 == null)
					{
						Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
						return;
					}
				}
				parser2.messageParsing();
				smsType = parser2.getSmsType();
				flagATM = parser2.getFlagATM();
				
				if (smsType == BDConstents.IN_SMS)
				{
					Toast.makeText(superContext, "수입/입금 문자입니다. 수입 탭으로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
					return;
				}
				else if (smsType == BDConstents.OUT_ATM_SMS || smsType == BDConstents.IN_ATM_SMS)
				{
					Toast.makeText(superContext, "현금 입/출금 문자입니다. 자산이동 메뉴로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
					return;
				}
				else if (checkRadioButton.isChecked() && smsType == BDConstents.HALBU_SMS)
				{
					Toast.makeText(superContext, "신용카드 할부 문자입니다. 신용카드 탭으로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
					return;
				}
				
//				if (!parser2.getAvailable()) 
//				{
//					SMSParser parser = new SMSParser(inputMessage);
//					parser.messageParsing();
//					smsType = parser.getSmsType();
//					if (smsType == BDConstents.IN_SMS)
//					{
//						Toast.makeText(superContext, "수입/입금 문자입니다. 수입 탭으로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
//						return;
//					}
//					else if (smsType == BDConstents.OUT_ATM_SMS || smsType == BDConstents.IN_ATM_SMS)
//					{
//						Toast.makeText(superContext, "현금 입/출금 문자입니다. 자산이동 메뉴로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
//						return;
//					}
//					else if (checkRadioButton.isChecked() && smsType == BDConstents.HALBU_SMS)
//					{
//						Toast.makeText(superContext, "신용카드 할부 문자입니다. 신용카드 탭으로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
//						return;
//					}
//					
//					if (!parser.getAvailable())
//					{
////						BDUtil.showDialog(SMSActivity.this, "연동불가문자", "지원하지 않는 문자 형식입니다.");
//						BDUtil.showToast(superContext, "지원하지 않는 문자 형식입니다..");
//						return;
//					}
//					
//					Toast.makeText(superContext, "정확하게 등록이 된 문자가 아닙니다. 해당 문자를 개발자에게 보내주시면 더 정확하게 사용이 가능합니다.", Toast.LENGTH_LONG).show();
//				}
				
//				for (int i=0; i<mArrayPaySMSData.size(); i++) {
//					if (inputNumber.equalsIgnoreCase(mArrayPaySMSData.get(i).getAddress())) {
////						BDUtil.showDialog(SMSActivity.this, "연동불가문자", "동일한 번호의 결제문자가 이미 등록되어 있습니다.");
//						BDUtil.showToast(SMSActivity.this, "동일한 번호의 연동문자가 이미 등록되어 있습니다.");
//						return;
//					}
//				}
				
				Intent intent = new Intent(InsertOutActivity.this, SMSSettingActivity.class);
				intent.putExtra("address", inputNumber);
				intent.putExtra("body", inputMessage);
				
				if (checkRadioButton.isChecked()) {
					intent.putExtra("kind", "체크카드");
				} else if (creditRadioButton.isChecked()) {
					intent.putExtra("kind", "신용카드");
				} else if (bankRadioButton.isChecked()) {
					intent.putExtra("kind", "통장");
				}
				
				intent.putExtra("where", "InsertOutActivity");
				startActivityForResult(intent, REQUEST_SMS);
				
				if (dialog != null) {
					dialog.dismiss();
					dialog = null;
				}
			}
		});
		dialogView.findViewById(R.id.smsDialog3_btnCancel).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (dialog != null) {
					dialog.dismiss();
					dialog = null;
				}
			}
		});
		
		dialog = builder.create();
		dialog.show();
	}
	
	private class SMSAdapter extends ArrayAdapter<SMSData> implements OnItemClickListener 
	{
		Context context;
		int viewId;
		ArrayList<SMSData> items;
		
		public SMSAdapter(Context context, int textViewResourceId, ArrayList<SMSData> objects) {
			super(context, textViewResourceId, objects);
			this.context = context;
			this.viewId = textViewResourceId;
			this.items = objects;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			
			if (view == null) {
				view = LayoutInflater.from(context).inflate(viewId, null);
			}
			
			SMSData data = items.get(position);
			
			((TextView) view.findViewById(R.id.listSMS2Address)).setText(data.getAddress());
			((TextView) view.findViewById(R.id.listSMS2Body)).setText(data.getBody());
			
			return view;
		}
		
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			
			linkCardName = "";
			
			int smsType = BDConstents.OUT_SMS;
			boolean flagATM = false;
			String halbuMonth = "1";
			//SMSParser2 parser = new SMSParser2(items.get(arg2).getBody());
			Parser parser = null;
			try {
				parser = new Parser(items.get(arg2).getBody());
			} catch (Exception e)
			{
				Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
				return;
			} finally
			{
				if (parser == null)
				{
					Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			parser.setDate(items.get(arg2).getDate());
			InputData data = new InputData();
			data = parser.messageParsing();
			smsType = parser.getSmsType();
			halbuMonth = parser.getHalbuMonth();
			flagATM = parser.getFlagATM();
			
			if (data == null || !parser.getAvailable())
			{
				BDUtil.showDialog(InsertOutActivity.this, "지원불가문자", "지원하지 않는 문자 형식입니다.");
				return;
			}
			
			if (!parser.getAvailable())
			{
				BDUtil.showDialog(InsertOutActivity.this, "지원불가문자", "지원하지 않는 문자 형식입니다.");
				return;
			}
			
			if (smsType == BDConstents.IN_SMS)
			{
				Toast.makeText(superContext, "수입/입금 문자입니다. 수입 탭으로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
				return;
			}
			else if (smsType == BDConstents.OUT_ATM_SMS || smsType == BDConstents.IN_ATM_SMS)
			{
				Toast.makeText(superContext, "현금 입/출금 문자입니다. 자산이동 메뉴로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
				return;
			}
			else if ( (checkRadioButton.isChecked() || bankRadioButton.isChecked()) && smsType == BDConstents.HALBU_SMS)
			{
				Toast.makeText(superContext, "신용카드 할부 문자입니다. 신용카드 탭으로 이동해서 사용해주세요.", Toast.LENGTH_LONG).show();
				return;
			}
			
			String address = items.get(arg2).getAddress();
			if ( ( (data.getMemo1() != null) || (data.getMemo2() != null) || (data.getMemo3() != null) || (data.getMemo4() != null) ) 
					&& data.getMemo1().equals(data.getMemo2()) && data.getMemo1().equals(data.getMemo3()) && data.getMemo1().equals(data.getMemo4()) 
					&& getPaySMSData(address, data.getName()) && checkType(linkCardName))
			{
				if (dialog != null) {
					dialog.dismiss();
					dialog = null;
				}
				
				String cardName = linkCardName;
				String date = data.getDate();
				String money = data.getMoney();
				String memo = data.getMemo1();
				
				if (smsType == BDConstents.HALBU_SMS)
				{
					Intent intent = new Intent(InsertOutActivity.this, AutoInsertActivity.class);
					intent.putExtra(AutoInsertActivity.REQUEST_KEY, AutoInsertActivity.INSERT_HALBU);
					intent.putExtra(AutoActivity.AUTO_UPDATE_DELECT_FLAG, AutoActivity.AUTO_INSERT);
					intent.putExtra(HALBU_CARD_NAME, linkCardName);
					intent.putExtra(HALBU_DATE, data.getDate());
					intent.putExtra(HALBU_MONEY, data.getMoney());
					intent.putExtra(HALBU_MEMO, data.getMemo1());
					intent.putExtra(HALBU_MONTH, halbuMonth);

					startActivityForResult(intent, REQUEST_HALBU);
					
					if (dialog != null) {
						dialog.dismiss();
						dialog = null;
					}
				}
				else 
				{
					try {
						dateTextView.setText(BDUtil.getDate(
								Integer.parseInt(date.substring(0, 4)), 
								Integer.parseInt(date.substring(4, 6)), 
								Integer.parseInt(date.substring(6, 8))));
						
						if (checkRadioButton.isChecked()) {
							checkTextView.setText(cardName);
							setBalanceCheckMoney();
						} else if (creditRadioButton.isChecked()) {
							creditTextView.setText(cardName);
							setBalanceCreditMoney();
						} else if (bankRadioButton.isChecked()) {
							bankTextView.setText(cardName);
							setBalanceBankMoney();
						} 
						
						InsertOutActivity.this.money.setText(money);
						
						InsertOutActivity.this.memo.setText(memo);
						
					} catch (Exception e) {
						
						Intent intent = new Intent(InsertOutActivity.this, SMSSettingActivity.class);
						intent.putExtra("date", items.get(arg2).getDate());
						intent.putExtra("address", items.get(arg2).getAddress());
						intent.putExtra("body", items.get(arg2).getBody());
						
						if (checkRadioButton.isChecked()) {
							intent.putExtra("kind", "체크카드");
						} else if (creditRadioButton.isChecked()) {
							intent.putExtra("kind", "신용카드");
						} else if (bankRadioButton.isChecked()) {
							intent.putExtra("kind", "통장");
						} 
						
						intent.putExtra("where", "InsertOutActivity");
						startActivityForResult(intent, REQUEST_SMS);
						
						if (dialog != null) {
							dialog.dismiss();
							dialog = null;
						}
					}
				}
			}
			else
			{
				if (smsType == BDConstents.HALBU_SMS)
				{
					Intent intent = new Intent(InsertOutActivity.this, AutoInsertActivity.class);
					intent.putExtra(AutoInsertActivity.REQUEST_KEY, AutoInsertActivity.INSERT_HALBU);
					intent.putExtra(AutoActivity.AUTO_UPDATE_DELECT_FLAG, AutoActivity.AUTO_INSERT);
					intent.putExtra(HALBU_CARD_NAME, linkCardName);
					intent.putExtra(HALBU_DATE, data.getDate());
					intent.putExtra(HALBU_MONEY, data.getMoney());
					intent.putExtra(HALBU_MEMO, data.getMemo1());
					intent.putExtra(HALBU_MONTH, halbuMonth);

					startActivityForResult(intent, REQUEST_HALBU);
					
					if (dialog != null) {
						dialog.dismiss();
						dialog = null;
					}
				}
				else
				{
					Intent intent = new Intent(InsertOutActivity.this, SMSSettingActivity.class);
					intent.putExtra("date", items.get(arg2).getDate());
					intent.putExtra("address", items.get(arg2).getAddress());
					intent.putExtra("body", items.get(arg2).getBody());
					
					if (checkRadioButton.isChecked()) {
						intent.putExtra("kind", "체크카드");
					} else if (creditRadioButton.isChecked()) {
						intent.putExtra("kind", "신용카드");
					} else if (bankRadioButton.isChecked()) {
						intent.putExtra("kind", "통장");
					} 
					
					intent.putExtra("where", "InsertOutActivity");
					startActivityForResult(intent, REQUEST_SMS);
					
					if (dialog != null) {
						dialog.dismiss();
						dialog = null;
					}
				}
			}
		}
	}
	
	private boolean checkType(String name)
	{
		flag = false;
		
		if (checkRadioButton.isChecked())
		{
			for (int i=0; i<checkList.size(); i++)
			{
				if (checkList.get(i).equalsIgnoreCase(name))
				{
					flag = true;
				}
			}
		}
		else if (bankRadioButton.isChecked())
		{
			for (int i=0; i<bankList.size(); i++)
			{
				if (bankList.get(i).equalsIgnoreCase(name))
				{
					flag = true;
				}
			}
		}
		else if (creditRadioButton.isChecked())
		{
			for (int i=0; i<creditList.size(); i++)
			{
				if (creditList.get(i).equalsIgnoreCase(name))
				{
					flag = true;
				}
			}
		}
		
		return flag;
	}
	
	private boolean flag = false;
	private String linkCardName;
	
	private boolean getPaySMSData(final String address, final String messageCardName) {
		
		String query = "";
		
		//Log.e("a", address);
		
		query = "SELECT messagecardname, linkcardname, linkcardtype, parser FROM sms where address= '" + 
				BDUtil.getApostrophe(address) + "' and messagecardname = '" + 
				BDUtil.getApostrophe(messageCardName) + "';";
		
		try {
			sql.selectMapTile(superContext, query, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
//					//Log.e("1", "resultData");
					int count = c.getCount();
					c.moveToFirst();
					
					if (count != 0)
					{
						//int addressIndex = c.getColumnIndex("address");
						//int nameIndex = c.getColumnIndex("name");
						int messageCardNameIndex = c.getColumnIndex("messagecardname");
						int linkCardNameIndex = c.getColumnIndex("linkcardname");
						
						for (int i = 0; i < count; i++)
						{
							if (messageCardName.equals(c.getString(messageCardNameIndex))) 
							{
								linkCardName = c.getString(linkCardNameIndex);
								//Log.e("a", "messageCardName : "+messageCardName);
								//Log.e("a", "linkCardName : "+linkCardName);
							}
							
							c.moveToNext();
						}
						
						flag = true;
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
			
			flag = false;
			return flag;
		}
		
		return flag;
	}
	
	private void setMacroDelete()
	{
		String [] whereArgs = new String[]{macroData.getId()};
		sql.delete(superContext, "macro_list", "id = ?", whereArgs);
	}
	
	private ArrayList<SMSData> list;
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog progressDialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				progressDialog = new ProgressDialog(InsertOutActivity.this);
				progressDialog.setCancelable(false);
				progressDialog.setMessage("Loading...");
				progressDialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						insertOutData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				else if (arg0[1] == 3) 
				{
					
					list = new SmsLoadInbox(superContext).loadSMS();
					
					if (list != null) 
					{
						return arg0[1];
					} 
					else 
					{
						return 4;
					}
				}
				else if (arg0[1] == 5)
				{
					setMacroDelete();
					
					return 5;
				}
				
				return arg0[0];
			}
			else
			{
				return arg0[0];
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (progressDialog != null) 
			{
				progressDialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1) 
			{
				//BDUtil.showDialogFinish(InsertOutActivity.this, "확인", "입력이 완료 되었습니다.");
				
				if (fromMacro)
				{
					String msg = "";
					
					if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_STRING))
					{
						msg = "입력이 완료 되었습니다.";
					}
					else if (from != null && from.equalsIgnoreCase(MacroListActivity.REQUEST_MACRO_UPDATE))
					{
						msg = "수정이 완료 되었습니다.";
					}
					
					BDUtil.showDialogFinish(superContext, "확인", msg);
				}
				else
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(superContext);
					builder.setTitle("입력 완료");
					builder.setMessage("입력이 완료 되었습니다.");
					builder.setIcon(android.R.drawable.ic_dialog_info);
					builder.setPositiveButton("확인", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							BDUtil.btnEnable = true;
							BDUtil.asyncFlag = 0;
							
							dialog.dismiss();
							finish();
						}
					});
					builder.setNegativeButton("추가입력", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							BDUtil.btnEnable = true;
							BDUtil.asyncFlag = 0;
							
							if (realRadioButton.isChecked())
							{
								//realRadioButton.performClick();
								setBalanceRealMoney();
								money.setText("");
								memo.setText("");
							}
							else if (checkRadioButton.isChecked())
							{
								//checkRadioButton.performClick();
								setBalanceCheckMoney();
								money.setText("");
								memo.setText("");
							}
							else if (bankRadioButton.isChecked())
							{
								//bankRadioButton.performClick();
								setBalanceBankMoney();
								money.setText("");
								memo.setText("");
							}
							else if (creditRadioButton.isChecked())
							{
								//creditRadioButton.performClick();
								setBalanceCreditMoney();
								money.setText("");
								memo.setText("");
							}
						}
					});
					
					builder.show();
				}
			}
			else if (result == 3) 
			{
				setAddListView(list);
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 4)
			{
				noSMS();
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 5)
			{
				BDUtil.showDialogFinish(superContext, "확인", "빠른 입력이 삭제되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
